let statsChart = null;

function initStats() {
    const canvas = document.getElementById('stats-chart');
    if (!canvas) return;

    const ctx = canvas.getContext('2d');
    if (statsChart) statsChart.destroy();

    const { labels, completedData, checkinData } = getStatsData();

    statsChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [
                {
                    label: '每日完成待办数',
                    data: completedData,
                    backgroundColor: 'rgba(79, 172, 254, 0.7)',
                    borderColor: 'rgba(79, 172, 254, 1)',
                    borderWidth: 1
                },
                {
                    label: '签到',
                    data: checkinData,
                    backgroundColor: 'rgba(46, 204, 113, 0.7)',
                    borderColor: 'rgba(46, 204, 113, 1)',
                    borderWidth: 1
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: { precision: 0 }
                }
            }
        }
    });
}

function getStatsData() {
    const dailyStats = JSON.parse(localStorage.getItem('dailyStats') || '[]');
    const labels = [];
    const completedData = [];
    const checkinData = [];

    // 最近7天
    for (let i = 6; i >= 0; i--) {
        const date = new Date();
        date.setDate(date.getDate() - i);
        const dateStr = date.toISOString().split('T')[0];
        const displayLabel = `${date.getMonth() + 1}/${date.getDate()}`;

        labels.push(displayLabel);

        const record = dailyStats.find(item => item.date === dateStr);
        completedData.push(record ? record.completedTodos : 0);
        checkinData.push(record?.checkedIn ? 1 : 0);
    }

    return { labels, completedData, checkinData };
}

function updateStatsData() {
    if (document.getElementById('stats-module').classList.contains('active')) {
        initStats();
    }
}

function cleanupStats() {
    if (statsChart) {
        statsChart.destroy();
        statsChart = null;
    }
}